//
//  PersonalInfoViewController.m
//  GolfFriend
//
//  Created by vescky on 14-2-5.
//  Copyright (c) 2014年 vescky.org. All rights reserved.
//

#import "PersonalInfoViewController.h"
#import "CacheDaoForCircleContent.h"
#import "AppsEngine.h"
#import "MJRefresh.h"
#import "CircleContentVO.h"
#import "GolfFriendCircleCell2.h"
#import "GolfFriendViewController.h"
#import "CircleDetailViewController.h"
#import "UserSession.h"
#import "UIImageView+MJWebCache.h"
#import "ContactBook.h"
#import "AppsEngine.h"
#import "OneToOneChatViewController.h"

#import "MyCommentsViewController.h"
#import "SettingViewController.h"

@interface PersonalInfoViewController ()<MJRefreshBaseViewDelegate,GolfFriendViewDelegate,UIActionSheetDelegate> {
    GolfFriendViewController *gfCircle;
    //下拉刷新，上拉加载更多
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    NSString *userId;
    bool isSelf;
}

@end

@implementation PersonalInfoViewController

@synthesize userInfo;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.navigationController.navigationBar setHidden:NO];
    [self setTitle:@"个人资料"];
    [super customBackButton];
    imgvAvatar.layer.cornerRadius = imgvAvatar.frame.size.width / 2.0;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self initView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initView {
    
    userId = [userInfo objectForKey:@"userId"];
    if ([[[UserSession shareUserSession] getUserId] isEqualToString:userId]) {
        isSelf = YES;
    }
    else {
        isSelf = NO;
    }
    
    //定制自己的风格的  UIBarButtonItem
    UIButton* publishButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 7, 30, 30)];//
    [publishButton setImage:[UIImage imageNamed:@"toolbar_more.png"] forState:UIControlStateNormal];
    [publishButton addTarget:self action:@selector(showMoreMenu) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* actionItem= [[UIBarButtonItem alloc] initWithCustomView:publishButton];
    [self.navigationItem setRightBarButtonItem:actionItem];
    
    //初始化刷新view
    _header = [MJRefreshHeaderView header];
    _header.scrollView = articleScrollView;
    _header.delegate = self;
    
    // 4.3行集成上拉加载更多控件
    _footer = [MJRefreshFooterView footer];
    _footer.scrollView = articleScrollView;
    _footer.delegate = self;
    
    gfCircle = [[GolfFriendViewController alloc] init];
    gfCircle.delegate = self;
    gfCircle.hostUserId = userId;
    [articleScrollView addSubview:gfCircle.view];
    [self oganizeSubviews];
    
    //自己
    if ([userId isEqualToString:[[UserSession shareUserSession] getUserId]]) {
        userInfo = [[NSMutableDictionary alloc] initWithDictionary:[[UserSession shareUserSession] getUserPublicInfo]];
    }
    else {
        if ([[ContactBook shareContactBook] isFriendExist:userId]) {
            userInfo = [[ContactBook shareContactBook] getUserInfo:userId];
        }
        else {
            //上网获取
            NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:userId,@"userIDs", nil];
            [[AppsEngine shareAppsEngine] submitRequest:@"gfGetUserInfo" param:params onCompletion:^(id jsonResponse) {
                NSArray *uList = [jsonResponse objectForKey:@"userInfoList"];
                if (isValueSet(uList)) {
                    [[ContactBook shareContactBook] saveVisitorList:[[NSMutableArray alloc] initWithArray:uList]];
                    //通讯录已更新
                    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_ContactBook_Refreshed object:nil];
                }
                userInfo = [[ContactBook shareContactBook] getUserInfo:userId];
                [self performSelectorOnMainThread:@selector(refreshInfo) withObject:nil waitUntilDone:YES];
            } onError:^(NSError *error) {
                
            } method:@"GET"];
        }
    }
    [self refreshInfo];
}

- (void)refreshInfo {
    if (!isValueSet(userInfo)) {
        return;
    }
    [imgvAvatar setImageURLStr:[userInfo objectForKey:@"avatar"] placeholder:Default_Avatar];
    [imgvTeamLogo setImageURLStr:[userInfo objectForKey:@"teamLogo"] placeholder:[UIImage imageNamed:@"default_team_logo.png"]];
    labelNickName.text = [userInfo objectForKey:@"nickName"];
    labelTeamName.text = [userInfo objectForKey:@"teamName"];
    labelMotto.text = [userInfo objectForKey:@"motto"];
}

- (void)oganizeSubviews {
    
    float gfCircleHeight = [gfCircle getTableViewHeightWithDataArray:nil];
    
    CGRect circleRect = gfCircle.view.frame;
    circleRect.origin.y = viewHead.frame.origin.y +  viewHead.frame.size.height;
    circleRect.size.height = gfCircleHeight;
    [gfCircle.view setFrame:circleRect];
    
    [articleScrollView setContentSize:CGSizeMake(self.view.frame.size.width, circleRect.origin.y + circleRect.size.height + 30)];
}

- (void)showMoreMenu {
    UIActionSheet *as = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拉进黑名单" otherButtonTitles:@"添加到通信录",@"和Ta聊天",@"举报Ta", nil];
    if (isSelf) {
        as = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"历史消息",@"修改资料", nil];
    }
    as.delegate = self;
    [as showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (isSelf) {
        if (buttonIndex == 0) {
            NSLog(@"历史消息");
            MyCommentsViewController *mcvc = [[MyCommentsViewController alloc] init];
            [self.navigationController pushViewController:mcvc animated:YES];
        }
        else if (buttonIndex == 1) {
            NSLog(@"修改资料");
            SettingViewController *svc = [[SettingViewController alloc] init];
            [self.navigationController pushViewController:svc animated:YES];
        }
        return;
    }
    
    if (buttonIndex == 0) {
        NSLog(@"拉黑");
    }
    else if (buttonIndex == 1) {
        NSLog(@"添加");
        [[ContactBook shareContactBook] saveFriend:userInfo];
        NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[[UserSession shareUserSession] getUserId],@"userID",userId,@"operateID",@"addFriend",@"operation",nil];
        [[AppsEngine shareAppsEngine] submitRequest:@"gfChangeFriendShip" param:params onCompletion:^(id jsonResponse) {
            NSLog(@"%@",jsonResponse);
        } onError:^(NSError *error) {
            NSLog(@"add friend fail!");
        } method:@"GET"];
    }
    else if (buttonIndex == 2) {
        NSLog(@"聊天");
        OneToOneChatViewController *cVc = [[OneToOneChatViewController alloc] init];
        [cVc setUserId:userId];
        [self.navigationController pushViewController:cVc animated:YES];
    }
    else if (buttonIndex == 3) {
        NSLog(@"举报");
    }
}

#pragma mark - 刷新的代理方法---进入下拉刷新\上拉加载更多都有可能调用这个方法
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if (refreshView == _header) {
        // 下拉刷新
        [gfCircle refreshContent];
    }
    else {
        //上拉加载更多
        [gfCircle loadMoreContent];
    }
}

#pragma mark - GolfFriendViewDelegate
- (void)refreshContentDidFinish {
    [_header endRefreshing];
    [self oganizeSubviews];
    NSLog(@">>>>>>>>>>>  Refresh end <<<<<<<<<<<<<<");
}
- (void)loadMoreContentDidFinish {
    [_footer endRefreshing];
    [self oganizeSubviews];
    NSLog(@">>>>>>>>>>>  Load More end <<<<<<<<<<<<<<");
}

- (void)didReachTheEndingPage {
//    [SVProgressHUD showSuccessWithStatus:@"已到达最后一页"];
}

- (void)addButtonPressed {
    
}

- (IBAction)btnAction:(id)sender {
    UIButton *btn = (UIButton*)sender;
    if (btn.tag == 201) {
        //201 添加
        [[ContactBook shareContactBook] saveFriend:userInfo];
        NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[[UserSession shareUserSession] getUserId],@"userID",
                                       userId,@"operateID",
                                       @"addFriend",@"operation",nil];
        [[AppsEngine shareAppsEngine] submitRequest:@"gfChangeFriendShip" param:params onCompletion:^(id jsonResponse) {
            NSLog(@"%@",jsonResponse);
        } onError:^(NSError *error) {
            NSLog(@"add friend fail!");
        } method:@"GET"];
    }
    else if (btn.tag == 202) {
        //202 聊天
        OneToOneChatViewController *cVc = [[OneToOneChatViewController alloc] init];
        [cVc setUserId:userId];
        [self.navigationController pushViewController:cVc animated:YES];
    }
    else if (btn.tag == 203) {
        //203 关注
    }
    
}


@end
